<?php
class Controller_skusalesshow extends Controller_Admin
{
    public function before()
    {
        try {
            ACL::Required('skusalesshow');
        } catch ( HTTP_Exception_403 $e ) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect ( URL::base (true) );
        }

        parent::before();
    }

    public function action_index()
    {
        $this->title=__("SKU销量趋势报表");
        $maxDate = date('Y-m-d', $_SERVER['REQUEST_TIME'] - 86400);
        $view = View::factory("skusalesshow");
        tool::slashesDeep($_GET);

        $sri = $this->whoSkus();
        //echo $sri;exit;
        $sql = "SELECT
            `sku`,
            SUM(`daysale7`) `daysale7`,
            SUM(`daysale14`) `daysale14`,
            SUM(`daysale28`) `daysale28`,
            SUM(`daysale`) `daysale`,
            `stage`
        FROM
            `sku_sales`
        WHERE
            `count_date` = '{$maxDate}'";

        empty($_GET['skuName']) || $sql .= " AND `sku` = '{$_GET['skuName']}'";                                     //过滤条件
        empty($_GET['skuNameLike']) || $sql .= " AND `sku` LIKE '%{$_GET['skuNameLike']}%'";//过滤条件
        $sri && $sql .= $sri;
        $sql .= " GROUP BY `sku`";
        empty($_GET['allStage']) || $sql .= ', `stage`';                                                            //全平台查询 || 分平台操作

        isset($_GET['download']) && $this->buildCsv($sql);
        if( ($count = $this->request->param('id', false)) === false ) {                                             //查询总长度
            $count = DB::query(Database::SELECT, 'SELECT COUNT(`id`) c FROM(SELECT `id` ' . substr($sql, 207)." ) a")
                ->execute('newerp')->get('c', 0);
        }

        empty($_GET['page']) && $_GET['page'] = 1;
        $_GET['page'] -= 1;
        $sql .= ' LIMIT ' . ($_GET['page'] * 50) . ', 50';
        $view->set('dataList',                                                                                      //数据列表
            DB::query(Database::SELECT, $sql)->execute('newerp')->as_array()
        );

        $pagination         = Pagination::factory(array(
            'items_per_page'  => 50,
            'total_items'     => $count,
            'uri'             => '/skusalesshow/index/' . $count,
        ));
        $view->set('last',DB::select('add_time')->from('sku_sales')->order_by('id','DESC')->limit(1)->execute('newerp')->get('add_time',''));
        $view->set('pagination', $pagination);                                                                      //分页列表

        $view->set('get',$_GET);
        $view->set('opera',User::active_user()->nick);
        $this->response->body($view);
    }

    /**
     * 描述 : 显示数据
     * 作者 : Edgar.lee
     */
    public function action_jsonData() {
        $mixDate = date('Y-m-d', $_SERVER['REQUEST_TIME'] - 2592000);                                               //30天前日期
        tool::slashesDeep($_GET);

        $date = array();
        for($i = 30; $i > 0; --$i) {
            $temp = date('m-d', $_SERVER['REQUEST_TIME'] - $i * 86400);
            $date[$temp] = 0;
        }

        $data = array(
            'date'  => array_keys($date),
            '1day'  => $date,
            '7day'  => $date,
            '14day' => $date,
            '28day' => $date
        );

        $sql = $_GET['stage'] === '0' ? '' : "AND `stage`='{$_GET['stage']}'";
        $sql = "SELECT
            SUM(`daysale7`) `daysale7`,
            SUM(`daysale14`) `daysale14`,
            SUM(`daysale28`) `daysale28`,
            SUM(`daysale`) `daysale`,
            DATE_FORMAT(`count_date`, '%m-%d') `date`
        FROM
            `sku_sales`
        WHERE
            `count_date` >= '{$mixDate}'
        AND `sku` = '{$_GET['sku']}'
        {$sql}
        GROUP BY
            `count_date`";

        $temp = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
        foreach($temp as &$v) {
            $data['1day'][$v['date']] = (int)$v['daysale'];
            $data['7day'][$v['date']] = (int)$v['daysale7'];
            $data['14day'][$v['date']] = (int)$v['daysale14'];
            $data['28day'][$v['date']] = (int)$v['daysale28'];
        }

        $data['1day'] = array_values($data['1day']);
        $data['7day'] = array_values($data['7day']);
        $data['14day'] = array_values($data['14day']);
        $data['28day'] = array_values($data['28day']);

        echo json_encode($data);
        exit;
    }

    public function buildCsv($sql) {
        set_time_limit(0);
        $_GET['date'] = date('Y-m-d', $_SERVER['REQUEST_TIME']);
        $md5 = md5(join('::',$_GET));

        $file = dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/disk/".$md5.".csv";

        if(!is_file($file)) {
            $fp =fopen($file, 'a+');
            flock($fp, LOCK_EX);
            ftruncate($fp, 0);

            fwrite($fp,iconv('UTF-8','GB18030//IGNORE','SKU,商品名,日均销量,7日内均销量,14日内均销量,28日内均销量,销售平台')."\r\n");

            $lists = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();

            if(!empty($lists)){
                $skus = array();
                $skus_str = '';
                foreach($lists as &$l)
                {
                    if(!empty($skus)) {
                        if(!in_array($l['sku'], $skus)) {
                            $skus[] = $l['sku'];
                            $skus_str .= $skus_str?",'".$l['sku']."'":"'".$l['sku']."'";
                        }
                    } else {
                        $skus[] = $l['sku'];
                        $skus_str .= $skus_str?",'".$l['sku']."'":"'".$l['sku']."'";
                    }
                }

                /*$client = new PHPRPC_Client();
                $client->useService("http://192.168.5.5:802/profitapi/execute");*/

                $sri = "SELECT a.`sku`,b.`name`
                    FROM `skusystem_cnname` as b
                    JOIN `skusystem_sku_cnname` as a
                    ON a.`attr_id`=b.`id`
                    WHERE a.`sku` IN ({$skus_str})";

                //$skus = json_decode($client->getinfo($sri),TRUE);
                $skus = DB::query(Database::SELECT,$sri)->execute('newerp')->as_array();
                $sku_ns = array();
                foreach($skus as $s){
                    $sku_ns[$s['sku']] = $s['name'];
                }

                foreach($lists as $list) {
                    if( empty($_GET['allStage']) ) {
                        $stage = '全平台';
                    } else {
                        switch( $list['stage'] ) {
                            case '1':
                                $stage = 'ebay';
                                break;
                            case '2':
                                $stage = '速卖通';
                                break;
                            case '3':
                                $stage = '亚马逊';
                                break;
                            case '4':
                                $stage = 'wish';
                                break;
                        }
                    }

                    $sku_name = isset($sku_ns[$list['sku']]) ? iconv('UTF-8','GB18030//IGNORE',$sku_ns[$list['sku']]) : '';
                    $stage = iconv('UTF-8','GB18030//IGNORE',$stage);
                    $temp = "\"{$list['sku']}\"\t,\"{$sku_name}\"\t,\"{$list['daysale']}\"\t,\"{$list['daysale7']}\"\t,\"{$list['daysale14']}\"\t,\"{$list['daysale28']}\"\t,\"{$stage}\"\t\r\n";
                    fwrite($fp,$temp);
                }
            }
            fclose($fp);
        }
        echo $md5;
        exit;
    }

    public function action_download() {
        set_time_limit(0);
        header('Content-Type: application/download'); //下载头
        header('Content-Transfer-Encoding: binary'); //二进制
        header('Content-Disposition: attachment; filename='.iconv('UTF-8','GB18030//IGNORE',"SKU销量预测报表{$_GET['date']}").'.csv'); //文件名
        header('Pragma:no-cache'); //不缓存

        $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/disk/'.$_GET['md5'].'.csv';
        $fp   = fopen($path,'r');
        flock($fp,LOCK_SH); //加共享锁
        while(!feof($fp)){ //读取数据
            echo fread($fp,8192);
        }
        fclose($fp);

        exit;
    }

    public function whoSkus() {
        $sri = '';$f = FALSE;
        if(isset($_GET['username'])){
            if($_GET['username']){
                $_skus = Skusystemapi::getUserAllSkuByNick($_GET['username']);
            }else{
                $f = TRUE;
            }
        }else{
            $_skus = Skusystemapi::getUserAllSkuByNick(User::active_user()->nick);
        }

        if(!$f){
            if($_skus){
                $skus_str = '';
                foreach($_skus as $_s){
                    $skus_str .= $skus_str?",'".$_s['sku']."'":"'".$_s['sku']."'";
                }
                $sri .= " AND `sku` IN ({$skus_str}) ";
            }else{
                $sri .= " AND `id`=0 ";
            }
        }

        return $sri;
    }

    //四大平台复合SKU拆单
    public function action_bitComplexSku () {
        $tbls = array('ebay', 'smt', 'amazon', 'wish');
        $t = date("Y-m-d", strtotime("-28 day"));
        foreach ($tbls as $tbl) {
            //四大平台老erp执行
            checkstock::bomb($tbl, $t);
            //去除四大平台海外仓部分
            checkstock::expCn($tbl, $t);
        }
        //去除速卖通中%号
        checkstock::expSum('smt');
    }

    public function action_executeSmt () {
        checkstock::expSum('smt');
    }

    public function action_badBegin() {
        checkstock::badBegin('ebay');
    }
}